package team.seekers.catering.common.handler.exceptionHandler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import team.seekers.catering.common.result.R;
import team.seekers.catering.common.result.ResultCode;

import java.nio.file.AccessDeniedException;



@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 这个注解表名此方法应该处理什么异常
    @ExceptionHandler(Exception.class)
    @ResponseBody//统一返回类型
    public R error(Exception e) {
        e.printStackTrace();
        return R.fail().message("执行了全局异常处理");
    }

    // 由于全局异常的存在只能手动捕获这个异常
    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public R handleAccessRE(AccessDeniedException ex){
        System.out.println(ex.getMessage());
        return R.fail(ResultCode.NO_PERMISSION);
    }

    // 自定义类异常的处理
    @ExceptionHandler(ResultException.class)
    @ResponseBody
    public R error(ResultException e) {
        e.printStackTrace();
        //返回错误码，统一返回类型方便调用
        return R.fail(ResultCode.GET_FAIL).message(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String s =  e.getBindingResult().getFieldError().getDefaultMessage();
        return R.fail(ResultCode.PARAM_NOT_VALID).message(s);
    }


}
